<template>
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden">
      <!-- 模态框头部 -->
      <div class="flex justify-between items-center p-6 border-b border-gray-200">
        <h2 class="text-xl font-semibold text-gray-900">
          {{ isEdit ? '编辑章节要点配置' : '新增章节要点配置' }}
        </h2>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600 transition-colors"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>
      </div>

      <!-- 模态框内容 -->
      <div class="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                章节号 <span class="text-red-500">*</span>
              </label>
              <input
                v-model.number="form.chapterNumber"
                type="number"
                :min="isEdit ? 1 : minChapterNumber"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入章节号"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                排序 <span class="text-red-500">*</span>
              </label>
              <input
                v-model.number="form.sortOrder"
                type="number"
                min="0"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入排序值"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                状态
              </label>
              <select
                v-model="form.isActive"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option :value="true">启用</option>
                <option :value="false">禁用</option>
              </select>
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              标题 <span class="text-red-500">*</span>
            </label>
            <input
              v-model="form.title"
              type="text"
              required
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入章节要点标题"
            />
          </div>

          <!-- 左侧内容配置 -->
          <div class="border border-gray-200 rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">左侧内容配置</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  标题 <span class="text-red-500">*</span>
                </label>
                <input
                  v-model="form.leftSection.title"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入左侧标题"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  图标
                </label>
                <select
                  v-model="form.leftSection.icon"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="lightning">⚡ 闪电</option>
                  <option value="book">📚 书本</option>
                  <option value="code">💻 代码</option>
                  <option value="tools">🔧 工具</option>
                  <option value="star">⭐ 星星</option>
                  <option value="target">🎯 目标</option>
                </select>
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                子节内容
              </label>
              <div class="space-y-3">
                <div
                  v-for="(subsection, index) in form.leftSection.subsections"
                  :key="index"
                  class="border border-gray-200 rounded-md p-3"
                >
                  <div class="flex justify-between items-center mb-2">
                    <span class="text-sm font-medium text-gray-700">子节 {{ index + 1 }}</span>
                    <button
                      type="button"
                      @click="removeLeftSubsection(index)"
                      class="text-red-600 hover:text-red-800 transition-colors"
                    >
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                      </svg>
                    </button>
                  </div>
                  
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-2 mb-2">
                    <input
                      v-model="subsection.title"
                      type="text"
                      placeholder="子节标题"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    />
                    <select
                      v-model="subsection.color"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="bg-blue-400">蓝色</option>
                      <option value="bg-green-400">绿色</option>
                      <option value="bg-red-400">红色</option>
                      <option value="bg-yellow-400">黄色</option>
                      <option value="bg-purple-400">紫色</option>
                      <option value="bg-pink-400">粉色</option>
                    </select>
                    <select
                      v-model="subsection.type"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="list">列表</option>
                      <option value="text">文本</option>
                    </select>
                  </div>
                  
                  <div v-if="subsection.type === 'list'">
                    <label class="block text-xs font-medium text-gray-600 mb-1">列表项（每行一项）</label>
                    <textarea
                      v-model="subsection.itemsText"
                      rows="3"
                      class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      placeholder="请输入列表项，每行一项"
                    ></textarea>
                  </div>
                  
                  <div v-else>
                    <label class="block text-xs font-medium text-gray-600 mb-1">文本内容</label>
                    <textarea
                      v-model="subsection.content"
                      rows="3"
                      class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      placeholder="请输入文本内容"
                    ></textarea>
                  </div>
                </div>
              </div>
              
              <button
                type="button"
                @click="addLeftSubsection"
                class="mt-2 text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                添加子节
              </button>
            </div>
          </div>

          <!-- 右侧内容配置 -->
          <div class="border border-gray-200 rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">右侧内容配置</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  标题 <span class="text-red-500">*</span>
                </label>
                <input
                  v-model="form.rightSection.title"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入右侧标题"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  图标
                </label>
                <select
                  v-model="form.rightSection.icon"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="lightning">⚡ 闪电</option>
                  <option value="book">📚 书本</option>
                  <option value="code">💻 代码</option>
                  <option value="tools">🔧 工具</option>
                  <option value="star">⭐ 星星</option>
                  <option value="target">🎯 目标</option>
                </select>
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                子节内容
              </label>
              <div class="space-y-3">
                <div
                  v-for="(subsection, index) in form.rightSection.subsections"
                  :key="index"
                  class="border border-gray-200 rounded-md p-3"
                >
                  <div class="flex justify-between items-center mb-2">
                    <span class="text-sm font-medium text-gray-700">子节 {{ index + 1 }}</span>
                    <button
                      type="button"
                      @click="removeRightSubsection(index)"
                      class="text-red-600 hover:text-red-800 transition-colors"
                    >
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                      </svg>
                    </button>
                  </div>
                  
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-2 mb-2">
                    <input
                      v-model="subsection.title"
                      type="text"
                      placeholder="子节标题"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    />
                    <select
                      v-model="subsection.color"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="bg-blue-400">蓝色</option>
                      <option value="bg-green-400">绿色</option>
                      <option value="bg-red-400">红色</option>
                      <option value="bg-yellow-400">黄色</option>
                      <option value="bg-purple-400">紫色</option>
                      <option value="bg-pink-400">粉色</option>
                    </select>
                    <select
                      v-model="subsection.type"
                      class="px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                    >
                      <option value="list">列表</option>
                      <option value="text">文本</option>
                    </select>
                  </div>
                  
                  <div v-if="subsection.type === 'list'">
                    <label class="block text-xs font-medium text-gray-600 mb-1">列表项（每行一项）</label>
                    <textarea
                      v-model="subsection.itemsText"
                      rows="3"
                      class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      placeholder="请输入列表项，每行一项"
                    ></textarea>
                  </div>
                  
                  <div v-else>
                    <label class="block text-xs font-medium text-gray-600 mb-1">文本内容</label>
                    <textarea
                      v-model="subsection.content"
                      rows="3"
                      class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      placeholder="请输入文本内容"
                    ></textarea>
                  </div>
                </div>
              </div>
              
              <button
                type="button"
                @click="addRightSubsection"
                class="mt-2 text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                添加子节
              </button>
            </div>
          </div>

          <!-- 提示信息配置 -->
          <div class="border border-gray-200 rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">提示信息配置</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  提示标签 <span class="text-red-500">*</span>
                </label>
                <input
                  v-model="form.tip.label"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入提示标签"
                />
              </div>
              <div class="md:col-span-1">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  提示内容 <span class="text-red-500">*</span>
                </label>
                <textarea
                  v-model="form.tip.content"
                  rows="3"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入提示内容"
                ></textarea>
              </div>
            </div>
          </div>
        </form>
      </div>

      <!-- 模态框底部 -->
      <div class="flex justify-end gap-3 p-6 border-t border-gray-200">
        <button
          type="button"
          @click="$emit('close')"
          class="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
        >
          取消
        </button>
        <button
          type="button"
          @click="handleSubmit"
          :disabled="saving"
          class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
        >
          <svg v-if="saving" class="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          {{ saving ? '保存中...' : (isEdit ? '更新' : '创建') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from 'vue'

// 环境变量配置
const API_BASE_URL = `http://${import.meta.env.VITE_BACKEND_HOST || 'localhost'}:${import.meta.env.VITE_BACKEND_PORT || '806'}`

// 类型定义
interface SubSection {
  title: string
  color: string
  type: 'list' | 'text'
  items?: string[]
  content?: string
  itemsText?: string // 用于表单编辑的临时字段
}

interface Section {
  title: string
  icon: string
  subsections: SubSection[]
}

interface Tip {
  label: string
  content: string
}

interface ChapterHighlight {
  id?: number
  chapterNumber: number
  title: string
  leftSection: Section
  rightSection: Section
  tip: Tip
  isActive: boolean
  sortOrder: number
}

// Props
interface Props {
  highlight?: ChapterHighlight | null
  isEdit: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  close: []
  save: [data: Partial<ChapterHighlight>]
}>()

// 状态
const saving = ref(false)
const minChapterNumber = ref(1)

// 计算属性
const isEdit = computed(() => !!props.highlight && props.isEdit)

// 表单数据
const form = reactive<ChapterHighlight>({
  chapterNumber: 1,
  title: '',
  leftSection: {
    title: '',
    icon: 'lightning',
    subsections: []
  },
  rightSection: {
    title: '',
    icon: 'book',
    subsections: []
  },
  tip: {
    label: '',
    content: ''
  },
  isActive: true,
  sortOrder: 0
})

// 初始化表单数据
const initializeForm = async () => {
  if (props.highlight && props.isEdit) {
    Object.assign(form, {
      ...props.highlight,
      leftSection: {
        ...props.highlight.leftSection,
        subsections: props.highlight.leftSection.subsections.map(sub => ({
          ...sub,
          itemsText: sub.items ? sub.items.join('\n') : ''
        }))
      },
      rightSection: {
        ...props.highlight.rightSection,
        subsections: props.highlight.rightSection.subsections.map(sub => ({
          ...sub,
          itemsText: sub.items ? sub.items.join('\n') : ''
        }))
      }
    })
  } else {
    // 获取下一个章节号
    const nextChapterNumber = await fetchMaxChapterNumber()
    minChapterNumber.value = nextChapterNumber
    
    // 重置为默认值
    Object.assign(form, {
      chapterNumber: nextChapterNumber,
      title: '',
      leftSection: {
        title: '',
        icon: 'lightning',
        subsections: []
      },
      rightSection: {
        title: '',
        icon: 'book',
        subsections: []
      },
      tip: {
        label: '',
        content: ''
      },
      isActive: true,
      sortOrder: 0
    })
  }
}

// 获取最大章节号
const fetchMaxChapterNumber = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-highlights/max-chapter-number`, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      return result.data.nextChapterNumber || 1
    }
  } catch (error) {
    console.error('获取最大章节号失败:', error)
  }
  return 1
}

// 监听 props 变化
watch(() => props.highlight, initializeForm, { immediate: true })

// 组件挂载时获取最大章节号
onMounted(async () => {
  const nextChapterNumber = await fetchMaxChapterNumber()
  minChapterNumber.value = nextChapterNumber
  // 如果是新增模式，同时设置表单的章节号
  if (!props.highlight) {
    form.chapterNumber = nextChapterNumber
  }
})

// 添加左侧子节
const addLeftSubsection = () => {
  form.leftSection.subsections.push({
    title: '',
    color: 'bg-blue-400',
    type: 'list',
    items: [],
    itemsText: ''
  })
}

// 删除左侧子节
const removeLeftSubsection = (index: number) => {
  form.leftSection.subsections.splice(index, 1)
}

// 添加右侧子节
const addRightSubsection = () => {
  form.rightSection.subsections.push({
    title: '',
    color: 'bg-blue-400',
    type: 'list',
    items: [],
    itemsText: ''
  })
}

// 删除右侧子节
const removeRightSubsection = (index: number) => {
  form.rightSection.subsections.splice(index, 1)
}

// 处理表单提交
const handleSubmit = async () => {
  saving.value = true
  
  try {
    // 处理子节数据，将 itemsText 转换为 items 数组
    const processedForm = {
      ...form,
      leftSection: {
        ...form.leftSection,
        subsections: form.leftSection.subsections.map(sub => {
          const processed = { ...sub }
          if (sub.type === 'list' && sub.itemsText) {
            processed.items = sub.itemsText.split('\n').filter(item => item.trim())
            delete processed.itemsText
          } else if (sub.type === 'text') {
            delete processed.items
            delete processed.itemsText
          }
          return processed
        })
      },
      rightSection: {
        ...form.rightSection,
        subsections: form.rightSection.subsections.map(sub => {
          const processed = { ...sub }
          if (sub.type === 'list' && sub.itemsText) {
            processed.items = sub.itemsText.split('\n').filter(item => item.trim())
            delete processed.itemsText
          } else if (sub.type === 'text') {
            delete processed.items
            delete processed.itemsText
          }
          return processed
        })
      }
    }
    
    emit('save', processedForm)
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
/* 模态框样式 */
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}
</style>